package pp;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pp.strategy.task.Task;
import pp.strategy.task.TaskStrategyEnum;
import pp.strategy.worktime.WorkTimeStrategyEnum;
import properties.AutoBGProperties;
import properties.WorkTimeBean;
import util.HttpRequest;
import util.StringUtils;

import java.io.IOException;
import java.rmi.RemoteException;
import java.util.*;

/**
 * @author liufei
 * @Description
 * @Date 2020/11/10 19:20
 */
public class PowerProject {
    private static final Logger logger = LoggerFactory.getLogger(PowerProject.class);
    private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKOJybB/0CQYeStbZZmr1SfgAKUou3cV7jT9abur5lin6Ct27CZe7XzmEYJu8fYnVmTYK1o6sioWP3Ji1ueEohDo/bzizFZDoxHp2pbKTefpc0HK6A+bLXo13xdBd+4up88Gz4YQmfHLbPhY+83z78stU/91ap10o/3XPfQ4xHBwIDAQAB";
    private HttpRequest httpRequest;
    private String name;
    private String pwd;
    private AutoBGProperties autoBGProperties;

    public PowerProject(HttpRequest httpRequest, AutoBGProperties autoBGProperties) {
        this.autoBGProperties = autoBGProperties;
        this.httpRequest = httpRequest;
        this.name = autoBGProperties.getUser();
        this.pwd = autoBGProperties.getPassword();
    }

    public boolean login() throws Exception {
        int count = 0;
        while (count++ <= 5) {
            Map<String, Object> map = new HashMap<>();
            pwd = RSAEncrypt.encrypt(pwd, PUBLIC_KEY);
            map.put("UserId", name);
            map.put("Password", pwd);
            map.put("loginType", "CA");
            map.put("CAPassword", "");
            CloseableHttpResponse response = httpRequest.post("http://192.168.120.173/MvcPages/Home/LoginPost", map);
            HttpEntity post = response.getEntity();
            String resultMsg = EntityUtils.toString(post);
            if (response.getStatusLine().getStatusCode() <= 200 && !resultMsg.contains("error")) {
                logger.info("登录成功");
                return true;
            }
            if (response.getStatusLine().getStatusCode() == 500) {
                logger.error("服务器异常[" + resultMsg + "]");
                System.exit(0);
            }
            if (resultMsg.contains("密码错误")) {
                logger.error("密码错误[" + resultMsg + "]");
                System.exit(0);
            }
            logger.info("登录失败[" + resultMsg + "]");
        }
        return false;
    }

    public String bg() throws Exception {
        IWorkTimeStrategy iWorkTimeStrategy = WorkTimeStrategyEnum.newStrategy(autoBGProperties.getReportForWorkType(), this);
        Map<String, WorkTimeBean> stringWorkTimeBeanMap = iWorkTimeStrategy.workTime(autoBGProperties);
        for (Map.Entry<String, WorkTimeBean> entry : stringWorkTimeBeanMap.entrySet()) {
            saveTimesheet(entry.getKey(), entry.getValue());
        }
        return printTimesheetFields();
    }

    /**
     * @param time         当天时间
     * @param workTimeBean 工时
     * @throws Exception
     */
    public void saveTimesheet(String time, WorkTimeBean workTimeBean) throws Exception {
        String standardHours = workTimeBean.getStandardHours();
        String overtimeHours = workTimeBean.getOvertimeHours();
        if (StringUtils.isBlank(standardHours) && StringUtils.isBlank(overtimeHours) ||
                overtimeHours.equals("0") && standardHours.equals("0")
        ) {
            return;
        }
        Map<String, Object> map1 = new HashMap<>();
        map1.put("Category1", "Task");
        map1.put("Category2", selectTask().getId());
        map1.put("ProjectId", getProjectIdByName(autoBGProperties.getProjectName()));
        map1.put("PreSaleProjectId", "");
        map1.put("UserId", name);
        map1.put("Date", time);
        map1.put("StandardHours", standardHours);
        map1.put("OvertimeHours", overtimeHours);
        map1.put("WorkType", autoBGProperties.getWorkType());
        map1.put("WorkContent", workTimeBean.getContext());
        CloseableHttpResponse post = httpRequest.post("http://192.168.120.173/Timesheets/Submit/SaveTimesheet", map1);
        logger.info(EntityUtils.toString(post.getEntity()));
    }

    /**
     * 选择任务
     *
     * @return
     */
    public Task selectTask() throws IOException {
        Map<String, Object> map1 = new HashMap<>();
        map1.put("category1", "Task");
        map1.put("projectId", getProjectIdByName(autoBGProperties.getProjectName()));
        map1.put("firstDayOfWeek", autoBGProperties.getFirstDay());
        CloseableHttpResponse post = httpRequest.post("http://192.168.120.173/Timesheets/Submit/GetTimesheetObjects", map1);
        String o = EntityUtils.toString(post.getEntity());
        JSONArray jsonArray = JSONObject.parseArray(o);
        if (jsonArray.size() == 0) {
            throw new RuntimeException("沒有找到任务，请联系项目经理安排任务");
        }
        IProjectJobStrategy iProjectJobStrategy = TaskStrategyEnum.newStrategy(autoBGProperties.getSelectTask());
        return iProjectJobStrategy.jobId(jsonArray, autoBGProperties);
    }

    public String printTimesheetFields() throws Exception {
        return printTimesheetFields(autoBGProperties.getFirstDay());
    }

    private String printTimesheetFields(String date) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("date", date);
        CloseableHttpResponse post = httpRequest.post("http://192.168.120.173/Timesheets/Submit/TimesheetList", map);
        String s = EntityUtils.toString(post.getEntity());
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONArray footer = jsonObject.getJSONArray("footer");
        JSONObject footer0 = footer.getJSONObject(0);
        StringBuffer sb = new StringBuffer("\n");
        sb.append("\n");
        sb.append("报工总工时：" + footer0.remove("Summary") + "小时\n");
        sb.append("\n");
        footer0.remove("Title");
        footer0.remove("Category");
        sb.append("\n");
        sb.append("工时详情\n");
        List<String> keyList = new ArrayList<>(footer0.keySet());
        keyList.sort((a, b) -> a.compareTo(b));
        for (String s1 : keyList) {
            sb.append(s1 + ":" + footer0.get(s1));
            sb.append("\n");
        }
        sb.append("\n");

        logger.info("==================================================================");
        logger.info(sb.toString());
        logger.info("==================================================================");
        return sb.toString();
    }


    public String getProjectIdByName(String projectName) throws IOException {
        Map<String, Object> map1 = new HashMap<>();
        map1.put("content", projectName);
        map1.put("allEnable", "true");
        map1.put("states", Arrays.asList("已立项"));
        map1.put("paging", "true");
        map1.put("page", 1);
        map1.put("size", 20);
        CloseableHttpResponse post = httpRequest.post("http://192.168.120.173/Common/ProjectFilter/ProjectListByCondition", map1);
        String s = EntityUtils.toString(post.getEntity());
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONArray projects = jsonObject.getJSONArray("Projects");
        if (projects.size() == 0) {
            throw new RemoteException("没有这个项目[" + projectName + "]");
        }
        String id = projects.getJSONObject(0).getString("id");
        return id.trim();
    }
}
